package combination;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @program: javase
 * @description: candidates 中的数字可以无限制重复被选取。
 * @author: luolidong
 * @create: 2021-06-21 11:29
 * @version: 1.0
 */
public class CombinationSum40 {
    List<List<Integer>> list = new ArrayList<>();

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        if(candidates.length==0) return list;
        Arrays.sort(candidates);
        dfs(candidates, target, new ArrayList<>(), 0);
        return list;
    }

    public void dfs(int[] candidates, int target, List<Integer> clist, int begin) {
        if (target < 0) return;
        if (target == 0) {
            list.add(new ArrayList<>(clist));
            return;
        }
        for (int i = begin; i < candidates.length; i++) {
            if(i>begin&&candidates[i]==candidates[begin]) continue;
            target -= candidates[i];
            clist.add(candidates[i]);
            dfs(candidates, target, clist, i+1);
            clist.remove(clist.size() - 1);
            target += candidates[i];
        }
    }

    public static void main(String[] args) {
        List<List<Integer>> list = new CombinationSum40().combinationSum(new int[]{10,1,2,7,6,1,5}, 8);
        for (List<Integer> l : list) {
            System.out.println(l);
        }
    }
}
